import * as ImagePicker from "expo-image-picker";
import * as Sharing from 'expo-sharing';
import { useState } from "react";
import { Image, Text, TouchableOpacity, View } from "react-native";

export default () => {
  const [localUri, setLocalUri] = useState("");

  async function openImagePickerAsync() {
    const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
    console.log(permissionResult);
    if (permissionResult.granted === false) {
      alert("请允许访问相册");
      return;
    }
    let pickerResult = await ImagePicker.launchImageLibraryAsync();
    if (pickerResult.canceled) {
      return;
    }
    setLocalUri(pickerResult.assets[0].uri);
    console.log(pickerResult.assets[0].uri);
  }

  const oepnShareImage = async () => {
    await Sharing.shareAsync(localUri);
  };

  function goBack() {
    setLocalUri("");
  }

  if (localUri) {
    return <View>
      <Image source={{ uri: localUri }} style={{ width: 200, height: 200 }} />
      <TouchableOpacity onPress={oepnShareImage}>
        <Text>分享照片</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={goBack}>
        <Text>重新选择</Text>
      </TouchableOpacity>
    </View>;
  }

  return <View>
    <TouchableOpacity onPress={openImagePickerAsync}>
      <Text>选择图片</Text>
    </TouchableOpacity>
  </View>;
};